package com.snopy.designPattern.structure.proxy.impl;

import com.snopy.designPattern.structure.proxy.Video;
import com.snopy.designPattern.structure.proxy.inter.ThirdPartyYouTubeLib;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * @author snopy
 * @version 1.0.0
 * @classname YouTubeCacheProxy
 * @description
 * @email 77912204@qq.com
 * @date 2022/03/03 21:47
 */
@Slf4j
public class YouTubeCacheProxy implements ThirdPartyYouTubeLib {
    private ThirdPartyYouTubeLib youTubeService;
    private HashMap<String,Video> cachePopular = new HashMap<>();
    private HashMap<String,Video> cacheAll = new HashMap<>();

    public YouTubeCacheProxy() {
        this.youTubeService = new ThirdPartyYouTubeClass();
    }

    @Override
    public HashMap<String, Video> popularVideos() {
        if (cachePopular.isEmpty()){
            cachePopular = youTubeService.popularVideos();
        }else {
            log.info("Retrieved list from cache.");
        }
        return cachePopular;
    }

    @Override
    public Video getVideo(String videoId) {
        Video video = cacheAll.get(videoId);
        if (video == null){
            video = youTubeService.getVideo(videoId);
            cacheAll.put(videoId,video);
        }else {
            log.info("Retrieved video '"+ videoId + "' from cache.");
        }
        return video;
    }
    public void reset(){
        cachePopular.clear();
        cacheAll.clear();
    }
}
